package logic

import (
	"context"
	"errors"
	modelsni "furni-net/models"
	"gorm.io/gorm"

	"furni-net/furnirpc/furnirpc"
	"furni-net/furnirpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ToolAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewToolAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ToolAddLogic {
	return &ToolAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ToolAddLogic) ToolAdd(in *furnirpc.ToolAddRequest) (*furnirpc.ToolAddResponse, error) {
	// todo: add your logic here and delete this line
	class := modelsni.Class{
		Model: gorm.Model{},
		Name:  in.ClassName,
	}
	err := modelsni.DB.Where("name=?", in.ClassName).FirstOrCreate(&class).Error
	if err != nil {
		return nil, errors.New("分类添加失败")
	}
	brand := modelsni.Brand{
		Model: gorm.Model{},
		Name:  in.BrandName,
	}
	err = modelsni.DB.Where("name=?", in.BrandName).FirstOrCreate(&brand).Error
	if err != nil {
		return nil, errors.New("品牌添加失败")
	}
	tool := modelsni.Tool{
		Model:   gorm.Model{},
		Name:    in.Name,
		Price:   float64(in.Price),
		Num:     int(in.Num),
		Img:     in.Img,
		Info:    in.Info,
		ClassId: int(class.ID),
		BrandId: int(brand.ID),
	}
	err = modelsni.DB.Debug().Create(&tool).Error
	if err != nil {
		return nil, errors.New("家具添加失败")
	}
	return &furnirpc.ToolAddResponse{
		ToolId: int64(tool.ID),
	}, nil
}
